﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Cognex.VisionPro.PMAlign;
using Cognex.VisionPro.ImageFile;
using Cognex.VisionPro;
using Cognex.VisionPro.ToolBlock;

namespace Delta
{
    public partial class PMAlignToolForm : Form
    {
        //定义字段
        public CogPMAlignTool cogPM = new CogPMAlignTool();
        public CogImageFileTool cogImageFile = new CogImageFileTool();
        public CogToolBlock cogToolBlock = new CogToolBlock();
        public CogRectangleAffine aROI = new CogRectangleAffine();
        public CogImage8Grey Image=null;

        public VisionSetForm SuperiorForm;

        /// <summary>
        /// 当前选中模板匹配控件名称
        /// </summary>
        public string SetPMAlignToolName;

        /// <summary>
        /// 当前选中模板
        /// </summary>
        public CogPMAlignTool PMAlignTool = new CogPMAlignTool();

        


        /// <summary>
        /// block路径
        /// </summary>
        public string BlockPath;


        public PMAlignToolForm(VisionSetForm form)
        {
            InitializeComponent();
            SuperiorForm = form;
        }
        //训练按钮时间触发
        private void bTrainImage_Click(object sender, EventArgs e)
        {
            try
            {
                //模板匹配图像输入
                (cogToolBlock.Tools[SetPMAlignToolName] as CogPMAlignTool).InputImage = Image;
                (cogToolBlock.Tools[SetPMAlignToolName] as CogPMAlignTool).Pattern.TrainImage = Image;
                //初始化训练区域
                CogRectangleAffine PatMaxTrainRegion = default(CogRectangleAffine);
                PatMaxTrainRegion = (cogToolBlock.Tools[SetPMAlignToolName] as CogPMAlignTool).Pattern.TrainRegion as CogRectangleAffine;

                if ((PatMaxTrainRegion != null))
                {
                    //训练区域赋初值
                    PatMaxTrainRegion.SetCenterLengthsRotationSkew(320, 240, 400, 400, 0, 0);
                    //界面显示训练区域画布
                    PatMaxTrainRegion.GraphicDOFEnable = CogRectangleAffineDOFConstants.Position | CogRectangleAffineDOFConstants.Rotation | CogRectangleAffineDOFConstants.Size;
                }
                //初始化查找区域
                CogRectangle PatMaxSearchRegion = new CogRectangle();
                //设置搜索框的颜色为洋红色
                PatMaxSearchRegion.Color = CogColorConstants.Magenta;
                cogPM.SearchRegion = PatMaxSearchRegion;
                //默认查找区域为图像大小
                PatMaxSearchRegion.SetCenterWidthHeight(Image.Width / 2, Image.Height / 2, Image.Width, Image.Height);
                //界面显示查找区域画布
                PatMaxSearchRegion.GraphicDOFEnable = CogRectangleDOFConstants.Position | CogRectangleDOFConstants.Size;
                PatMaxSearchRegion.Interactive = true;
                cogRecordDisplay1.InteractiveGraphics.Clear();
                //清空界面上的画布
                cogRecordDisplay1.StaticGraphics.Clear();
                //界面上显示训练区域
                cogRecordDisplay1.InteractiveGraphics.Add(PatMaxTrainRegion, "test", false);
                //界面上显示查找区域
                cogRecordDisplay1.InteractiveGraphics.Add(PatMaxSearchRegion, "test", false);
                richTextBox1.Text += "抓取训练图像成功！\r\n";
                //cogPM.Run();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString(), "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }


        }

        private void bOpenImage_Click(object sender, EventArgs e)
        {
            try
            {
                cogRecordDisplay1.InteractiveGraphics.Clear();
                cogRecordDisplay1.StaticGraphics.Clear();
                string path;
                OpenFileDialog ofd = new OpenFileDialog(); // 实例一个打开文件的对象
                ofd.Filter = "bmpFile(*.bmp;*.jpg)|*.bmp;*.jpg"; // 实际起过滤作用的为|后面的部分
                if (ofd.ShowDialog() == DialogResult.OK) //弹出打开文件的弹窗，在点确定后执行
                {
                    path = ofd.FileName; //将文件路径传给变量 path
                    cogImageFile.Operator.Open(path, CogImageFileModeConstants.Read);//第一个为图片路径，第二个为打开的方式;
                    cogImageFile.Run();
                    Image = (CogImage8Grey)cogImageFile.OutputImage;//若要用到CogImage8Grey，需要显式转换一次
                    cogRecordDisplay1.Image = Image;//界面上显示打开的图像
                    cogRecordDisplay1.Fit(true);
                    richTextBox1.Text += "图像打开成功！\r\n";
                }
            }
            catch (Exception ex)
            {
                richTextBox1.Text += "图像打开失败！\r\n";
                MessageBox.Show(ex.ToString(), "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }

        }

        private void bTrain_Click(object sender, EventArgs e)
        {
            try
            {
                if ((cogToolBlock.Tools[SetPMAlignToolName] as CogPMAlignTool).Pattern != null && (cogToolBlock.Tools[SetPMAlignToolName] as CogPMAlignTool).Pattern.TrainImage != null && (cogToolBlock.Tools[SetPMAlignToolName] as CogPMAlignTool).Pattern.TrainRegion != null)//首先判断模板工具是否为空
                {
                    (cogToolBlock.Tools[SetPMAlignToolName] as CogPMAlignTool).Pattern.Train();//模板工具运行训练
                    Cognex.VisionPro.ICogRecord tmpRecord = (cogToolBlock.Tools[SetPMAlignToolName] as CogPMAlignTool).CreateCurrentRecord();//初始化Cognex记录工具，用以记录模板工具状态
                    //cogPM.Pattern.TrainImage = cogPM.InputImage;
                    tmpRecord = tmpRecord.SubRecords["TrainImage"];
                    cogRecordDisplay1.Record = tmpRecord;//显示训练原点
                    cogRecordDisplay1.Fit(true);
                    richTextBox1.Text += "模板训练成功！\r\n";
                }
                else
                {
                    richTextBox1.Text += "模板训练失败！\r\n";
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString(), "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            SetPMAlignToolName = "";
            if(comboBox1.Items.Count>0)
            {
                comboBox1.SelectedIndex = 0;
            }
        }
        
        public void LoadBlock(string Path)
        {
            cogToolBlock = CogSerializer.LoadObjectFromFile(Path) as CogToolBlock;
            BlockPath = Path;

            
            comboBox1.Items.Clear();
            comboBox1.Items.AddRange(GetAllToolNamesFromBlock(cogToolBlock).ToArray());
        }
        /// <summary>
        /// 获取block模板工具
        /// </summary>
        /// <param name="rootBlock"></param>
        /// <returns></returns>
        public List<string> GetAllToolNamesFromBlock(CogToolBlock rootBlock)
        {
            return GetAllToolNames(rootBlock, "");
        }

        /// <summary>
        /// 递归获取模板工具
        /// </summary>
        /// <param name="tool"></param>
        /// <param name="parentPath"></param>
        /// <returns></returns>
        public List<string> GetAllToolNames(ICogTool tool, string parentPath = "")
        {
            List<string> toolNames = new List<string>();

            

            if (tool is CogToolBlock toolBlock)
            {
                
                for (int i = 0; i < toolBlock.DisabledTools.Count; i++)
                {
                    SuperiorForm.UnEnabled.Add(cogToolBlock.DisabledTools[i].Name);
                }

                // 构建当前ToolBlock的路径前缀
                string currentPath = string.IsNullOrEmpty(parentPath)
                    ? toolBlock.Name
                    : $"{parentPath}.{toolBlock.Name}";

                if(!SuperiorForm.UnEnabled.Contains(toolBlock.Name))
                {
                    // 递归处理ToolBlock内的所有子工具
                    foreach (ICogTool subTool in toolBlock.Tools)
                    {
                        toolNames.AddRange(GetAllToolNames(subTool, currentPath));
                    }
                }
                
            }
            else
            {
                if (tool is CogPMAlignTool)
                {
                    // 普通工具：添加父路径前缀
                    string fullName = string.IsNullOrEmpty(parentPath)
                        ? tool.Name
                        : $"{parentPath}.{tool.Name}";

                    toolNames.Add(fullName);
                }
                
            }

            return toolNames;
        }



        //高级设置显示完整的模板工具界面
        private void bAdvancedSet_Click(object sender, EventArgs e)
        {

            CogPMAlignToolForm CogToolForm = new CogPMAlignToolForm(this);
            CogToolForm.Show();
        }
        //模板匹配运行
        private void bRun_Click(object sender, EventArgs e)
        {
            try
            {
                if(Image!=null)
                {
                    PMAlignTool.InputImage = Image;
                    PMAlignTool.Run();
                    CogPMAlignResults results = PMAlignTool.Results;
                    if (results.Count != 0)
                    {
                        //初始化显示画布
                        CogCompositeShape resultGraphicsOrigin = default(CogCompositeShape);
                        CogCompositeShape resultGraphicsMatchRegion = default(CogCompositeShape);
                        //画布绑定模板匹配的结果匹配区域
                        resultGraphicsOrigin = results[0].CreateResultGraphics(CogPMAlignResultGraphicConstants.Origin);
                        resultGraphicsMatchRegion = results[0].CreateResultGraphics(CogPMAlignResultGraphicConstants.MatchRegion);
                        cogRecordDisplay1.InteractiveGraphics.Clear();//清空界面显示
                        cogRecordDisplay1.StaticGraphics.Clear();//清空界面显示
                        cogRecordDisplay1.InteractiveGraphics.Add(resultGraphicsOrigin, "test", false);//添加运行结果显示画布到界面
                        cogRecordDisplay1.InteractiveGraphics.Add(resultGraphicsMatchRegion, "test", false);//添加运行结果显示画布到界面
                        richTextBox1.Text += "模板匹配成功！" + "--" + "匹配数量：" + results.Count.ToString() + "--" + "得分：" + results[0].Score.ToString() + "\r\n";
                    }
                    else
                    {
                        richTextBox1.Text += "模板匹配失败！\r\n";
                    }
                }
                

            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString(), "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }

        }

        private void bCentralOrigins_Click(object sender, EventArgs e)
        {
            try
            {
                if ((cogToolBlock.Tools[SetPMAlignToolName] as CogPMAlignTool).Pattern != null && (cogToolBlock.Tools[SetPMAlignToolName] as CogPMAlignTool).Pattern.TrainImage != null && (cogToolBlock.Tools[SetPMAlignToolName] as CogPMAlignTool).Pattern.TrainRegion != null)
                {
                    //定位后坐标绑定
                    ICogTransform2D transform = (cogToolBlock.Tools[SetPMAlignToolName] as CogPMAlignTool).Pattern.TrainImage.GetTransform(".", (cogToolBlock.Tools[SetPMAlignToolName] as CogPMAlignTool).Pattern.TrainRegion.SelectedSpaceName);
                    //将训练区域的矩形框赋给新建的矩形字段
                    CogRectangle rectangle = (cogToolBlock.Tools[SetPMAlignToolName] as CogPMAlignTool).Pattern.TrainRegion.Map(transform, CogCopyShapeConstants.GeometryOnly).EnclosingRectangle(CogCopyShapeConstants.GeometryOnly);
                    (cogToolBlock.Tools[SetPMAlignToolName] as CogPMAlignTool).Pattern.Origin.TranslationX = rectangle.CenterX;
                    (cogToolBlock.Tools[SetPMAlignToolName] as CogPMAlignTool).Pattern.Origin.TranslationY = rectangle.CenterY;
                    richTextBox1.Text += "抓取中心原点成功！\r\n";
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString(), "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void bSave_Click(object sender, EventArgs e)
        {
            CogSerializer.SaveObjectToFile(cogToolBlock, BlockPath);
            
            richTextBox1.Text += "工具保存成功！\r\n";
        }

        private void bClose_Click(object sender, EventArgs e)
        {
            this.Close();
        }
        //滚动信息显示最新一行
        private void richTextBox1_TextChanged(object sender, EventArgs e)
        {
            richTextBox1.SelectionStart = richTextBox1.TextLength;
            richTextBox1.ScrollToCaret();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            cogToolBlock = CogSerializer.LoadObjectFromFile(Application.StartupPath + @"\Vpp\3225CF\DeltaVpp.vpp") as CogToolBlock;
        }

        private void bCamera_Click(object sender, EventArgs e)
        {

        }

        private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
        {
            SetPMAlignToolName = comboBox1.Text;

            string[] PathName = SetPMAlignToolName.Split('.');

            ICogTool cogTool=null;
            for (int i = 1; i < PathName.Length; i++)
            {
                if(cogTool== null)
                {
                    cogTool = cogToolBlock.Tools[PathName[i]];
                }
                else
                {
                    CogToolBlock block = cogTool as CogToolBlock;
                    cogTool = block.Tools[PathName[i]];
                }
                if(cogTool is CogPMAlignTool)
                {
                    PMAlignTool = cogTool as CogPMAlignTool;
                    cogRecordDisplay1.Image = null;
                    cogRecordDisplay1.StaticGraphics.Clear();

                    if (PMAlignTool.InputImage != null)
                    {
                        cogRecordDisplay1.Image = PMAlignTool.InputImage;
                        Image = (CogImage8Grey)PMAlignTool.InputImage;
                        bRun_Click(sender, e);
                    }
                    else
                    {
                        Image = null;
                    }
                }
            }

        }
    }
}

